<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
const router = useRouter();

// API（可替换为实际接口）
// import api from '../../api/hy';

// 筛选条件
const filter = reactive({
  name: '',
  status: '',
  valid: '',
  start: '',
  end: ''
});

// 表格数据
const tableData = ref<any[]>([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const form = reactive({
  id: '',
  name: '',
  type: '',
  product: '',
  threshold: '',
  value: '',
  valid: '',
  time: [],
  status: ''
});
const formRef = ref();
const rules = {
  name: [ { required: true, message: '请输入优惠券名称', trigger: 'blur' } ],
  type: [ { required: true, message: '请选择类型', trigger: 'change' } ],
  value: [ { required: true, message: '请输入面值', trigger: 'blur' } ],
  time: [ { required: true, message: '请选择有效期', trigger: 'change' } ]
};

// mock 数据
const mockList = [
  {
    id: '1',
    name: '全品类通用券',
    type: '全场赠券',
    product: '全部商品',
    threshold: '满101元可用',
    value: '100元',
    valid: '2021-03-02 ~ 2017-03-12',
    status: '未过期'
  },
  {
    id: '2',
    name: '全品类通用券',
    type: '注册赠券',
    product: '指定商品',
    threshold: '无限制',
    value: '100元',
    valid: '2021-03-02 ~ 2017-03-12',
    status: '未过期'
  },
  {
    id: '3',
    name: '全品类通用券',
    type: '购物赠券',
    product: '指定分类',
    threshold: '满101元可用',
    value: '100元',
    valid: '2021-03-02 ~ 2017-03-12',
    status: '未过期'
  },
  {
    id: '4',
    name: '全品类通用券',
    type: '全场赠券',
    product: '全部商品',
    threshold: '满101元可用',
    value: '100元',
    valid: '2021-03-02 ~ 2017-03-12',
    status: '已过期'
  }
];

function fetchTableData() {
  loading.value = true;
  setTimeout(() => {
    // 模拟筛选和分页
    let list = mockList.filter(item => {
      return (
        (!filter.name || item.name.includes(filter.name)) &&
        (!filter.status || item.status === filter.status)
      );
    });
    total.value = list.length;
    tableData.value = list.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
    loading.value = false;
  }, 300);
}

onMounted(fetchTableData);

function handleSearch() {
  currentPage.value = 1;
  fetchTableData();
}
function handleReset() {
  Object.assign(filter, { name: '', status: '', valid: '', start: '', end: '' });
  currentPage.value = 1;
  fetchTableData();
}
function handlePageChange(val: number) {
  currentPage.value = val;
  fetchTableData();
}
function handleSizeChange(val: number) {
  pageSize.value = val;
  fetchTableData();
}

function handleCreate() {
  isEdit.value = false;
  Object.assign(form, { id: '', name: '', type: '', product: '', threshold: '', value: '', valid: '', time: [], status: '' });
  dialogVisible.value = true;
}
function handleEdit(row: any) {
  router.push(`/operation/coupon/edit/${row.id}`);
}
async function handleSubmit() {
  await formRef.value.validate();
  if (isEdit.value) {
    // 编辑
    const idx = mockList.findIndex(item => item.id === form.id);
    if (idx > -1) {
      mockList[idx] = { ...form, valid: form.time.join(' ~ ') };
      ElMessage.success('编辑成功');
    }
  } else {
    // 新建
    mockList.push({ ...form, id: Date.now() + '', valid: form.time.join(' ~ '), status: '未过期' });
    ElMessage.success('新建成功');
  }
  dialogVisible.value = false;
  fetchTableData();
}
async function handleDelete(row: any) {
  await ElMessageBox.confirm('确定要删除该优惠券吗？', '提示', { type: 'warning' });
  const idx = mockList.findIndex(item => item.id === row.id);
  if (idx > -1) {
    mockList.splice(idx, 1);
    ElMessage.success('删除成功');
    fetchTableData();
  }
}
function handleView(row: any) {
  router.push(`/operation/coupon/detail/${row.id}`);
}
</script>

<template>
  <div style="padding: 32px 0; background: #fafafa; min-height: 100vh;">
    <!-- 筛选区 -->
    <el-card style="margin: 0 auto; max-width: 1600px;">
      <el-form :inline="true" :model="filter" class="filter-form" style="margin-bottom: 12px;">
        <el-form-item label="优惠券名称">
          <el-input v-model="filter.name" placeholder="请输入内容" clearable style="width: 180px;" />
        </el-form-item>
        <el-form-item label="活动状态">
          <el-select v-model="filter.status" placeholder="全部" style="width: 140px;">
            <el-option label="全部" value="" />
            <el-option label="未过期" value="未过期" />
            <el-option label="已过期" value="已过期" />
          </el-select>
        </el-form-item>
        <el-form-item label="有效期">
          <el-select v-model="filter.valid" placeholder="有效期" style="width: 120px;">
            <el-option label="有效期" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-date-picker
            v-model="filter.start"
            type="date"
            placeholder="开始时间"
            style="width: 130px;"
          />
          <span style="margin: 0 8px;">至</span>
          <el-date-picker
            v-model="filter.end"
            type="date"
            placeholder="结束时间"
            style="width: 130px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">检索</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="danger" @click="handleCreate">新建优惠券</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区 -->
    <el-card style="margin: 32px auto 0; max-width: 1600px;">
      <el-table :data="tableData" border style="width: 100%;" :loading="loading">
        <el-table-column prop="name" label="优惠券名称" min-width="180" />
        <el-table-column prop="type" label="优惠券类型" min-width="120" />
        <el-table-column prop="product" label="可使用商品" min-width="120" />
        <el-table-column prop="threshold" label="使用门槛" min-width="120" />
        <el-table-column prop="value" label="面值" min-width="80" align="center" />
        <el-table-column prop="valid" label="有效期" min-width="220" />
        <el-table-column prop="status" label="状态" min-width="100" align="center" />
        <el-table-column label="操作" min-width="180" align="center">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex; align-items: center; justify-content: space-between; margin-top: 16px;">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, total, sizes"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
          :page-sizes="[10, 20, 50, 100]"
        />
        <span style="color: #d33; font-size: 15px;">当前条件共检索到 {{ total }} 条相关信息</span>
      </div>
    </el-card>

    <!-- 新建/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑优惠券' : '新建优惠券'" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择">
            <el-option label="全场赠券" value="全场赠券" />
            <el-option label="注册赠券" value="注册赠券" />
            <el-option label="购物赠券" value="购物赠券" />
          </el-select>
        </el-form-item>
        <el-form-item label="可使用商品">
          <el-input v-model="form.product" placeholder="如：全部商品/指定商品/指定分类" />
        </el-form-item>
        <el-form-item label="使用门槛">
          <el-input v-model="form.threshold" placeholder="如：满101元可用/无限制" />
        </el-form-item>
        <el-form-item label="面值" prop="value">
          <el-input v-model="form.value" placeholder="如：100元" />
        </el-form-item>
        <el-form-item label="有效期" prop="time">
          <el-date-picker v-model="form.time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 16px;
}
</style>